#include <private/qobject_p.h>
#include <QList>
#include <QMap>

#include "utilsprivate.h"
#include "idbinder.h"


IdBinder::IdBinder(QObject *parent):BasePropertyBinder(parent)
{

}

IdBinder::~IdBinder()
{

}

QStringList IdBinder::propertys() const
{
    return m_propertys;
}

void IdBinder::setPropertys(const QStringList &newProperty)
{
    if (m_propertys == newProperty)
        return;
    m_propertys = newProperty;
    update();
    emit propertysChanged();
}

static void addPropertys(QObject* o1,QObject* o2,const QStringList& propertys,BasePropertyBinder::BindDataList& output){
    for(auto i :propertys)
    {
        auto m1 = o1->metaObject();
        auto m2 = o2->metaObject();
        auto p1 = m1->property(m1->indexOfProperty(i.toLocal8Bit()));
        auto p2 = m2->property(m2->indexOfProperty(i.toLocal8Bit()));

        if(!p1.isValid() || !p2.isValid())
        {
            continue;
        }

        if(!p1.hasNotifySignal())
        {
            continue;
        }

        BasePropertyBinder::BindData data;
        data.dst = o2;
        data.dstProp = p2;
        data.src = o1;
        data.srcProp = p1;
        output.push_back(data);
    }
}

BasePropertyBinder::BindDataList IdBinder::generateBindList()
{
    if(m_propertys.empty())
    {
        return {};
    }

    BasePropertyBinder::BindDataList ret;
    auto sourceMap = UtilsPrivate::groupById(source());
    auto targetMap = UtilsPrivate::groupById(target());

    for(auto i:sourceMap.keys())
    {
        if(targetMap.contains(i))
        {
            addPropertys(sourceMap[i],targetMap[i],m_propertys,ret);
        }
    }

    return ret;
}


